package com.toidep.payment;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.activities.LoginActivity;
import com.toidep.activities.MainActivity;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.api.ResultObject;
import com.toidep.config.Constants;
import com.toidep.interfaces.ConfirmListener;
import com.toidep.interfaces.DialogListener;
import com.toidep.interfaces.ResponseListener;
import com.toidep.preference.SharePreference;
import com.toidep.utilities.DialogUtility;

public class PaymentControl {
	
	public static final int CHARGE_BY_SUB = 1;
	public static final int CHARGE_BY_CARD = 2;
	public static final int CHANGE_PHONE = 3;
	public static final int CHANGE_PHONE_OTP = 4;

	private Activity activity;
	private ResponseListener mResponseListener;
	private String mTitle = null;
	private boolean isPaymentSuccessfull = false;
	
	public PaymentControl(Activity activity) {
		this.activity = activity;
	}

	public void startPayment(ResponseListener responseListener) {
		mResponseListener = responseListener;
		
		DialogUtility.showDialogConfirm(activity, "", activity.getString(R.string.text_payment_request),
			new ConfirmListener() {
				
				@Override
				public void doCancel() {
					if (mResponseListener != null)
						mResponseListener.processResponse(-1);
				}
				
				@Override
				public void doAccept() {
					checkLogin();
				}
			});
	}
	
	public void setListener(ResponseListener responseListener) {
		mResponseListener = responseListener;
	}
	
	public void setTitle(String title) {
		mTitle = title;
	}
	
	private void checkLogin() {
		SharePreference ioeShare = SharePreference.getInstance(activity);
		if (ioeShare.getLoginStatus())
			showDialogPaymentStart();
		else { 
			Intent intent = new Intent(activity, LoginActivity.class);
			activity.startActivityForResult(intent, Constants.REQUEST_CODE_LOGIN_FOR_PAYMENT);
		}
	}
	
	/**
	 * Man hinh hoi nguoi dung chon lua hinh thuc de xem phim
	 */
	public void showDialogPaymentStart() {
		final Dialog dialog = new Dialog(activity, R.style.PopupTheme);

		dialog.setContentView(R.layout.fragment_payment);
		
		final RadioButton optionSub = (RadioButton) dialog.findViewById(R.id.optionSub);
		final RadioButton optionCard = (RadioButton) dialog.findViewById(R.id.optionCard);
		
		((ImageButton) dialog.findViewById(R.id.buttonSlide)).setVisibility(View.GONE);
		((ImageButton) dialog.findViewById(R.id.buttonSearch)).setVisibility(View.INVISIBLE);
		
		String title = activity.getString(R.string.label_support_payment).toUpperCase();
		((TextView) dialog.findViewById(R.id.textViewLabelSideBar)).setText(title);
		
		((Button) dialog.findViewById(R.id.button_continue)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (optionSub.isChecked()) {
					doPaymentBySub();
				} else if (optionCard.isChecked()) {
					doPaymentByCard();
				}
			}
		});
		
		((Button) dialog.findViewById(R.id.button_cancel)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		
		((ImageButton) dialog.findViewById(R.id.buttonBack)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		
		dialog.setCancelable(true);
		dialog.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				if (!isPaymentSuccessfull && mResponseListener != null) {
					mResponseListener.processResponse(-1);
				}
			}
		});
		dialog.show();
	}
	
	public void doPaymentBySub() {
		final Dialog dialog = new Dialog(activity, R.style.PopupTheme);

		dialog.setContentView(R.layout.layout_payment_sub);
		
		((ImageButton) dialog.findViewById(R.id.buttonSlide)).setVisibility(View.GONE);
		((ImageButton) dialog.findViewById(R.id.buttonSearch)).setVisibility(View.INVISIBLE);
		
		String title = mTitle == null ? activity.getString(R.string.label_support_payment).toUpperCase() 
									  : mTitle.toUpperCase();
		((TextView) dialog.findViewById(R.id.textViewLabelSideBar)).setText(title);
		
		((ImageButton) dialog.findViewById(R.id.buttonBack)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		
		dialog.setCancelable(true);
		dialog.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
//				if (!isPaymentSuccessfull) {
//					mResponseListener.processResponse(-1);
//				}
			}
		});
		dialog.show();

		final EditText edt_phone_number = (EditText) dialog.findViewById(R.id.edt_phone_number);
		SharePreference sharePreference = SharePreference.getInstance(activity);
		final String phoneNumberCurr = sharePreference.getUserPhone();
		if (phoneNumberCurr != null && !phoneNumberCurr.equals(""))
			edt_phone_number.setText(phoneNumberCurr);
		
		((Button) dialog.findViewById(R.id.button_sent_otp)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String phoneNumberNew = edt_phone_number.getText().toString().trim();
				// invalid cardCode
				if (phoneNumberNew == null || phoneNumberNew.equals("")) {
					DialogUtility.showDialogAlert(activity, "",
							activity.getString(R.string.text_payment_error_input_phone),
							activity.getString(R.string.label_close), new DialogListener() {
								
								@Override
								public void after() {
									showKeyBoard(edt_phone_number);
								}
							});
					return;
				}
				
//				if (phoneNumberNew.equals(phoneNumberCurr)) {
//					DialogUtility.showDialogAlert(activity, "",
//							"Số điện thoại "+phoneNumberNew+" đang được dùng!",
//							activity.getString(R.string.label_close), new DialogListener() {
//								
//								@Override
//								public void after() {
//									showKeyBoard(edt_phone_number);
//								}
//							});
//					return;
//				}
				
				
				ApiController.chargeBySub(activity,  phoneNumberNew, new ResponseListener() {
					
					@Override
					public void processResponse(int inintstall) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void processResponse(String response) {
						Log.e("response", response);
						try {
							JSONObject jsonObject = new JSONObject(response);
							int code = ParseJSON.getIntValue(jsonObject, Constants.PARAM_RESPONSE_CODE);
							if(code == 0){
//								if(activity instanceof MainActivity){
//									MainActivity main = (MainActivity) activity;
//									main.login();
//								}
								DialogUtility.showDialogAlert(activity, "",
										ParseJSON.getStringValue(jsonObject, "message"),
									activity.getString(R.string.label_close), null);
							}
							else if(code >0) {
								DialogUtility.showDialogAlert(activity, "",
										ParseJSON.getStringValue(jsonObject, "message"),
									activity.getString(R.string.label_close), null);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});
			}
		});
		
		final EditText edt_otp = (EditText) dialog.findViewById(R.id.edt_otp);	
		((Button) dialog.findViewById(R.id.button_accept)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final String phoneNumberNew = edt_phone_number.getText().toString().trim();
				// invalid cardCode
				if (phoneNumberNew == null || phoneNumberNew.equals("")) {
					DialogUtility.showDialogAlert(activity, "",
							activity.getString(R.string.text_payment_error_input_phone),
							activity.getString(R.string.label_close), new DialogListener() {
								
								@Override
								public void after() {
									showKeyBoard(edt_phone_number);
								}
							});
					return;
				}
			
				String otp = edt_otp.getText().toString().trim();
				// invalid cardCode
				if (otp == null || otp.equals("")) {
					DialogUtility.showDialogAlert(activity, "",
							activity.getString(R.string.text_payment_error_input_otp),
							activity.getString(R.string.label_close), new DialogListener() {
								
								@Override
								public void after() {
									showKeyBoard(edt_otp);
								}
							});
					return;
				}
				
				// Dang ky Sub voi So dien thoai da nhap
				ApiController.chargeBySub(activity,  phoneNumberNew, otp, new ResponseListener() {
					
					@Override
					public void processResponse(int inintstall) {
						// TODO Auto-generated method stub
					}
					
					@Override
					public void processResponse(String response) {
						Log.e("response", response);
						try {
							JSONObject jsonObject = new JSONObject(response);
							int code = ParseJSON.getIntValue(jsonObject, Constants.PARAM_RESPONSE_CODE);
//							if(code == 0){
//								if(activity instanceof MainActivity){
//									MainActivity main = (MainActivity) activity;
//									main.login();
//								}
//							}
//							else 
								if(code>0) {
								// Dang ky dich vu thanh cong
								SharePreference.getInstance(activity).putUserPhone(phoneNumberNew);
								
								if (mResponseListener != null){
									mResponseListener.processResponse(1);
								}
								//Bug #228 -start
								DialogUtility.showDialogAlert(activity, "", ParseJSON.getStringValue(jsonObject, "message"),
										activity.getString(R.string.label_close), null);
								//Bug #228 -end
								
							} else {
								DialogUtility.showDialogAlert(activity, "",
										ParseJSON.getStringValue(jsonObject, "message"),
									activity.getString(R.string.label_close), null);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});
			}
		});
	}
	
	private void doPaymentByCard() {
		final Dialog dialog = new Dialog(activity, R.style.PopupTheme);

		dialog.setContentView(R.layout.layout_payment_card);
		
		((ImageButton) dialog.findViewById(R.id.buttonSlide)).setVisibility(View.GONE);
		((ImageButton) dialog.findViewById(R.id.buttonSearch)).setVisibility(View.INVISIBLE);
		
		String title = mTitle == null ? activity.getString(R.string.label_support_payment).toUpperCase() 
								: mTitle.toUpperCase();
		((TextView) dialog.findViewById(R.id.textViewLabelSideBar)).setText(title);
		
		((ImageButton) dialog.findViewById(R.id.buttonBack)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		
		dialog.setCancelable(true);
		dialog.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
//				if (!isPaymentSuccessfull) {
//					mResponseListener.processResponse(-1);
//				}
			}
		});
		dialog.show();
		
		final CheckBox checkBoxVina = (CheckBox) dialog.findViewById(R.id.checkBoxVina);
		final CheckBox checkBoxViettel = (CheckBox) dialog.findViewById(R.id.checkBoxViettel);
		final CheckBox checkBoxMobi = (CheckBox) dialog.findViewById(R.id.checkBoxMobi);
		final CheckBox checkBoxVietNam = (CheckBox) dialog.findViewById(R.id.checkBoxVietnamMobi);
		final EditText edtCardCode = (EditText) dialog.findViewById(R.id.edtCardCode);
		final EditText edtCardSeri = (EditText) dialog.findViewById(R.id.edtCardSeri);
		
		hideKeyBoard(edtCardCode);
		hideKeyBoard(edtCardSeri);
		
		((Button) dialog.findViewById(R.id.button_ok)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// invalid telco
				if (telcoId == -1) {
					DialogUtility.showDialogAlert(activity, "",
							activity.getString(R.string.text_payment_error_input_telco),
							activity.getString(R.string.label_close), null);
					return;
				}
				
				// vinaphone: VNP, viettel: VTE, vnmobile: VNM, mobifone: VMS 
				String operator = checkBoxVina.isChecked() ? "VNP" : checkBoxViettel.isChecked() ? "VTE" :
						checkBoxVietNam.isChecked() ? "VNM" : checkBoxMobi.isChecked() ? "VMS" : "";
				String code = edtCardCode.getText().toString().trim();
				String serial = edtCardSeri.getText().toString().trim();
				
				// invalid cardCode
				if (code == null || code.equals("")) {
					DialogUtility.showDialogAlert(activity, "",
							activity.getString(R.string.text_payment_error_input_card_code),
							activity.getString(R.string.label_close), new DialogListener() {
								
								@Override
								public void after() {
									showKeyBoard(edtCardCode);
								}
							});
					return;
				}
				// invalid cardSerial
				if (serial == null || serial.equals("")) {
					DialogUtility.showDialogAlert(activity, "",
							activity.getString(R.string.text_payment_error_input_card_serial),
							activity.getString(R.string.label_close), new DialogListener() {
								
								@Override
								public void after() {
									showKeyBoard(edtCardSeri);
								}
							});
					return;
				}
				
				// payment
				ApiController.chargeByCard(activity, code, serial, operator, new ResponseListener() {
					
					@Override
					public void processResponse(int inintstall) {
						DialogUtility.showDialogAlert(activity, "",
								activity.getString(R.string.text_payment_request_error),
								activity.getString(R.string.label_close), null);
					}
					
					@Override
					public void processResponse(String response) {
						ResultObject resultObject = ParseJSON.getPaymentResult(response);
						if (resultObject != null) {
//							int code = resultObject.getCode();
//							if(code == 0){
//								if(activity instanceof MainActivity){
//									MainActivity main = (MainActivity) activity;
//									main.login();
//								}
//							} 
							//Bug #227 - start
							 if (resultObject.getCode() == 1) {
							//Bug #227 - end
								isPaymentSuccessfull = true;
								//Bug #228 -start
								DialogUtility.showDialogAlert(activity, "", "Bạn đã nạp "+resultObject.getAmount()+" VND vào tài khoản",
										activity.getString(R.string.label_close), new DialogListener() {
											
											@Override
											public void after() {
//												dialog.cancel();
												if (mResponseListener != null)
												mResponseListener.processResponse(1);
											}
										});
								//Bug #228 -end
							} else {
								DialogUtility.showDialogAlert(activity, "", resultObject.getMessage(),
										activity.getString(R.string.label_close), null);
							}
						}
					}
				});
			}
		});
		
		checkBoxVina.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (telcoId == TELCO_VINAPHONE) {
					telcoId = -1;
					checkBoxVina.setChecked(false);
				} else {
					telcoId = TELCO_VINAPHONE;
					checkBoxVina.setChecked(true);
				}
					
				checkBoxViettel.setChecked(false);
				checkBoxMobi.setChecked(false);
				checkBoxVietNam.setChecked(false);
			}
		});
		
		checkBoxViettel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (telcoId == TELCO_VIETTEL) {
					telcoId = -1;
					checkBoxViettel.setChecked(false);
				} else {
					telcoId = TELCO_VIETTEL;
					checkBoxViettel.setChecked(true);
				}
					
				checkBoxVina.setChecked(false);
				checkBoxMobi.setChecked(false);
				checkBoxVietNam.setChecked(false);
			}
		});
		
		checkBoxMobi.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (telcoId == TELCO_MOBIPHONE) {
					telcoId = -1;
					checkBoxMobi.setChecked(false);
				} else {
					telcoId = TELCO_MOBIPHONE;
					checkBoxMobi.setChecked(true);
				}
					
				checkBoxVina.setChecked(false);
				checkBoxViettel.setChecked(false);
				checkBoxVietNam.setChecked(false);
			}
		});
		
		checkBoxVietNam.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (telcoId == TELCO_VIETNAM_MOBILE) {
					telcoId = -1;
					checkBoxVietNam.setChecked(false);
				} else {
					telcoId = TELCO_VIETNAM_MOBILE;
					checkBoxVietNam.setChecked(true);
				}
					
				checkBoxVina.setChecked(false);
				checkBoxViettel.setChecked(false);
				checkBoxMobi.setChecked(false);
			}
		});
	}
	
	private final int TELCO_VINAPHONE = 1;
	private final int TELCO_VIETTEL = 2;
	private final int TELCO_MOBIPHONE = 3;
	private final int TELCO_VIETNAM_MOBILE = 4;

	private int telcoId = -1;
	
	/************** Untils Methods ***************/
	
	public void showKeyBoard(EditText editText) {
		if (editText != null) {
			editText.setFocusable(true);
			editText.setFocusableInTouchMode(true);
			editText.requestFocus();
			InputMethodManager inputMethodManager = ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE));
			inputMethodManager.showSoftInput(editText, 1);
		}
	}
	
	public void hideKeyBoard(EditText editText) {
		if (editText != null) {
			((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE)).
				hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	private ProgressDialog progressDialog;
	
	public void showProgressDialog() {
		if (progressDialog == null) {
			progressDialog = ProgressDialog.show(activity, null, activity.getString(R.string.text_processing), true);
			progressDialog.setCancelable(false);
		}
	}

	public void closeProgressDialog() {
		if (progressDialog != null) {
			progressDialog.cancel();
			progressDialog = null;
		}
	}

	/************** Untils Methods - End ***************/
}
